package com.wanchuang.qhbb.module.account;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.wanchuang.qhbb.R;
import com.wanchuang.qhbb.adapter.ZhangDanAdapter;
import com.wanchuang.qhbb.adapter.ZhangDanBean;
import com.wanchuang.qhbb.base.BaseActivity;
import com.wanchuang.qhbb.dialog.SelectDateDialog;
import com.wanchuang.qhbb.dialog.SelectMonthDialog;
import com.wanchuang.qhbb.net.Apis;
import com.wanchuang.qhbb.net.NetworkManager;
import com.wanchuang.qhbb.net.interfaces.OnRequestCallBack;
import com.wanchuang.qhbb.proto.Recharge;
import com.wanchuang.qhbb.utils.DateUtil;
import com.wanchuang.qhbb.utils.GsonUtils;
import com.wanchuang.qhbb.utils.ValidateUtils;
import com.wanchuang.qhbb.view.LoadMoreBottomView;
import com.wanchuang.qhbb.view.pinnedheader.PinnedHeaderItemDecoration;
import com.wanchuang.qhbb.view.pinnedheader.PinnedHeaderRecyclerView;
import com.google.android.material.tabs.TabLayout;
import com.google.protobuf.InvalidProtocolBufferException;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import kale.ui.view.dialog.EasyDialog;

public class ZhangDanActivity extends BaseActivity implements ZhangDanAdapter.OnTimeClickListener {

    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.recycler_linear)
    PinnedHeaderRecyclerView recyclerLinear;
    @BindView(R.id.refreshLayout)
    TwinklingRefreshLayout mRefreshLayout;
    @BindView(R.id.tv_select_month)
    TextView tvSelectMonth;
    @BindView(R.id.tv_tong_ji)
    TextView tvTongJi;
    @BindView(R.id.empty_view)
    LinearLayout emptyView;

    @BindView(R.id.ll_dong_jie)
    LinearLayout llDongJie;

    @BindView(R.id.tv_dong_jie_one)
    TextView tv_dong_jie_one;

    @BindView(R.id.tv_dong_jie_two)
    TextView tv_dong_jie_two;

    @BindView(R.id.tv_dong_jie_three)
    TextView tv_dong_jie_three;


    private List<ZhangDanBean> list = new ArrayList<>();
    private LinearLayoutManager layoutManager;
    private String walletType;
    private String type;
    private String countMonth;
    private List<Recharge.Earnings_detail_list.Earnings_detail_array_list> dayResult = new ArrayList<>();   // 每天数据
    private List<Recharge.EarningsStatics> monthResult = new ArrayList<>();// 月份每天数据
    private ZhangDanAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhang_dan);
        ButterKnife.bind(this);
        initView();
        initRefresh();
        initEvent();
        initData();
    }


    /**
     * 实例化下拉Refresh
     * *
     */
    private void initRefresh() {
        SinaRefreshView header = new SinaRefreshView(mContext);
        header.setArrowResource(R.mipmap.refresh_arrow);
        header.setBackgroundResource(R.color.backgroundColor);
        TextView refreshTextView = header.findViewById(com.lcodecore.tkrefreshlayout.R.id.tv);
        refreshTextView.setTextSize(14);
        mRefreshLayout.setHeaderView(header);
        LoadMoreBottomView bottom = new LoadMoreBottomView(mContext);
        mRefreshLayout.setBottomView(bottom);
        mRefreshLayout.setEnableLoadmore(true);
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                Recharge.Earnings_detail_list.Builder builder = Recharge.Earnings_detail_list.newBuilder();
                String searchtime = "";
                if (ValidateUtils.isValidate(dayResult)) {
                    searchtime = dayResult.get(0).getTime();
                } else {
                    return;
                }
                builder.setType(type).setWalletType(walletType).setAction("top").setTime(searchtime).setSearchMonth(countMonth);
                Log.e("onRefresh", builder.build().toString());
                NetworkManager.INSTANCE.post(Apis.Earnings_detail_list, builder.build().toByteArray(), new OnRequestCallBack() {
                    @Override
                    public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                        List<Recharge.Earnings_detail_list.Earnings_detail_array_list> addDayResult = Recharge.Earnings_detail_list.parseFrom(bytes).getEarningsDetailArrayListList();
                        Log.e("addDayResult", addDayResult.toString());
                        List<Recharge.Earnings_detail_list.Earnings_detail_array_list> tempDayResult = new ArrayList<>(addDayResult);
                        tempDayResult.addAll(dayResult);
                        dayResult = tempDayResult;
                        // 进行数据整理
                        sortData();
                        mRefreshLayout.finishRefreshing();
                    }

                    @Override
                    public void onError(int code, String errorMessage) {
                        hideProgress();
                        showToast(errorMessage);
                    }
                });
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                Recharge.Earnings_detail_list.Builder builder = Recharge.Earnings_detail_list.newBuilder();
                String searchtime = "";
                if (ValidateUtils.isValidate(dayResult)) {
                    searchtime = dayResult.get(dayResult.size() - 1).getTime();
                } else {
                    return;
                }
                builder.setType(type).setWalletType(walletType).setAction("bottom").setTime(searchtime).setSearchMonth(countMonth);
                NetworkManager.INSTANCE.post(Apis.Earnings_detail_list, builder.build().toByteArray(), new OnRequestCallBack() {
                    @Override
                    public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                        List<Recharge.Earnings_detail_list.Earnings_detail_array_list> addDayResult = Recharge.Earnings_detail_list.parseFrom(bytes).getEarningsDetailArrayListList();
                        Log.e("addDayResult", addDayResult.toString());
                        dayResult.addAll(addDayResult);
                        // 进行数据整理
                        sortData();
                        mRefreshLayout.finishLoadmore();
                    }

                    @Override
                    public void onError(int code, String errorMessage) {
                        hideProgress();
                        showToast(errorMessage);
                    }
                });
            }
        });
    }


    public View getTabView(String tabName) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.tab_select_two_layout, null);
        TextView tv_tab = view.findViewById(R.id.tv_tab);
        tv_tab.setText(tabName);
        return view;
    }


    private void initView() {
        tvTitle.setText(getIntent().getType() + "账单");
        Recharge.Tab tab = GsonUtils.deSerializedFromJson(getIntent().getStringExtra("tab"), Recharge.Tab.class);
        walletType = tab.getWalletType();
        for (Recharge.Item item : tab.getItemListList()) {
            TabLayout.Tab tab1 = tabLayout.newTab();
            tab1.setCustomView(getTabView(item.getTitle()));
            tab1.setTag(item.getType());
            tabLayout.addTab(tab1);
        }
        tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ffffff"));

        layoutManager = new LinearLayoutManager(this);
        recyclerLinear.setLayoutManager(layoutManager);
        mAdapter = new ZhangDanAdapter(list, this::onClick);
        recyclerLinear.setAdapter(mAdapter);
        recyclerLinear.addItemDecoration(new PinnedHeaderItemDecoration());
        countMonth = DateUtil.getYearMonth("yyyy-MM");
        tvSelectMonth.setText(DateUtil.getYearMonth("yyyy年MM月"));
        type = tabLayout.getTabAt(0).getTag().toString();
        tvSelectMonth.setOnClickListener(v -> {
            SelectMonthDialog.Builder builder = new SelectMonthDialog.Builder(mContext);
            builder.setOnDialogClickListener((view, year, month) -> {
                tvSelectMonth.setText(year + "年" + month + "月");
                countMonth = year + "-" + month;
                dayResult.clear();
                monthResult.clear();
                if (type.equals("freeze")) {
                    llDongJie.setVisibility(View.VISIBLE);
                    loadDongJie();
                } else {
                    llDongJie.setVisibility(View.GONE);
                }
                initData();
            });
            EasyDialog build = builder.build();
            build.setCancelable(true);
            build.show(getSupportFragmentManager());
        });

    }


    private void initEvent() {
        backIv.setOnClickListener(v -> finish());
        recyclerLinear.setOnPinnedHeaderClickListener(adapterPosition -> {
            Recharge.EarningsStatics title;
            title = list.get(adapterPosition).getTitle();
            String day = title.getYmdDate().substring(title.getYmdDate().length() - 2);
            String year = title.getYmdDate().substring(0, 4);
            String month = title.getYmdDate().substring(4, 6);
            onClick(null, year, month, day);
        });
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                type = tab.getTag().toString();

                if (type.equals("freeze")) {
                    llDongJie.setVisibility(View.VISIBLE);
                    loadDongJie();
                } else {
                    llDongJie.setVisibility(View.GONE);
                }
                dayResult.clear();
                monthResult.clear();
                initData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void loadDongJie() {
        NetworkManager.INSTANCE.post(Apis.freeze_money, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Recharge.freeze_money freeze_money = Recharge.freeze_money.parseFrom(bytes);
                tv_dong_jie_one.setText("￥"+freeze_money.getTotal());
                tv_dong_jie_two.setText("￥"+freeze_money.getSelf());
                tv_dong_jie_three.setText("￥"+freeze_money.getTeam());
            }

            @Override
            public void onError(int code, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });

    }

    private void initData() {
        showProgress();
        // 1.获取当前月份
        Recharge.earnings_detail_statics.Builder builder = Recharge.earnings_detail_statics.newBuilder();
        builder.setSearchMonth(countMonth).setType(type).setWalletType(walletType);
        Log.e("params", "initData: " + countMonth + " " + type + " " + walletType);
        NetworkManager.INSTANCE.post(Apis.earnings_detail_statics, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                String totalString = Recharge.earnings_detail_statics.parseFrom(bytes).getTotalInfo();
                if (ValidateUtils.isValidate(totalString)) {
                    if (totalString.contains(";")) {
                        String[] totoalSplit = totalString.split(";");
                        String totalOne = totoalSplit[0] + "\n" + totoalSplit[1];
                        tvTongJi.setText(totalOne);
                    } else {
                        tvTongJi.setText(totalString);
                    }
                }else
                {
                    tvTongJi.setText("");
                }


                List<Recharge.EarningsStatics> addMonthResult = Recharge.earnings_detail_statics.parseFrom(bytes).getEarningsStaticsListList();
                monthResult.addAll(addMonthResult);
                Log.e("wang", monthResult.toString() + "  " + totalString);
                // 获取每天的数据
                loadFirstDayData();
            }

            @Override
            public void onError(int code, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });
    }

    private void loadFirstDayData() {
        Recharge.Earnings_detail_list.Builder builder = Recharge.Earnings_detail_list.newBuilder();
        builder.setType(type).setWalletType(walletType).setSearchMonth(countMonth);
        NetworkManager.INSTANCE.post(Apis.Earnings_detail_list, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                hideProgress();
                List<Recharge.Earnings_detail_list.Earnings_detail_array_list> addDayResult = Recharge.Earnings_detail_list.parseFrom(bytes).getEarningsDetailArrayListList();
                dayResult.addAll(addDayResult);
                // 进行数据整理
                sortData();
            }

            @Override
            public void onError(int code, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });
    }

    private void sortData() {
        list.clear();
        String currrentTime = "";
        // 遍历天的数据
        for (int i = 0; i < dayResult.size(); i++) {
            if (!currrentTime.equals(DateUtil.getStrTime(dayResult.get(i).getTime()))) {
                currrentTime = DateUtil.getStrTime(dayResult.get(i).getTime());  // 获取时间戳的前半段
                for (int j = 0; j < monthResult.size(); j++) {
                    // 找到当前时间与列表返回时间相同
                    if (currrentTime.equals(monthResult.get(j).getYmdDate())) {
                        ZhangDanBean titleBean = new ZhangDanBean();
                        titleBean.setTitle(monthResult.get(j));
                        titleBean.setType(1);  // 标题
                        list.add(titleBean);
                        break;
                    }
                }
            }
            ZhangDanBean contentBean = new ZhangDanBean();
            contentBean.setType(0); // 内容
            contentBean.setContent(dayResult.get(i));
            list.add(contentBean);
        }

        if (ValidateUtils.isValidate(list)) {
            recyclerLinear.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
        } else {
            recyclerLinear.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        }

        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v, String year, String month, String day) {
        SelectDateDialog.Builder builder = new SelectDateDialog.Builder(mContext);
        builder.setOnDialogClickListener((v1, dialog, day1) -> {
            // 判断是否可以是在那天可选
            boolean isInsert = false;
            for (int i = 0; i < monthResult.size(); i++) {
                if (monthResult.get(i).getYmdDate().substring(monthResult.get(i).getYmdDate().length() - 2).equals(day1)) {
                    isInsert = true;
                    break;
                }
            }
            if (isInsert) {
                Recharge.Earnings_detail_list.Builder builder1 = Recharge.Earnings_detail_list.newBuilder();
                builder1.setType(type).setWalletType(walletType).setSearchDay(countMonth + "-" + day1).setSearchMonth(countMonth);
                NetworkManager.INSTANCE.post(Apis.Earnings_detail_list, builder1.build().toByteArray(), new OnRequestCallBack() {
                    @Override
                    public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                        dayResult.clear();
                        List<Recharge.Earnings_detail_list.Earnings_detail_array_list> addDayResult = Recharge.Earnings_detail_list.parseFrom(bytes).getEarningsDetailArrayListList();
                        dayResult.addAll(addDayResult);
                        // 进行数据整理
                        sortData();
                    }

                    @Override
                    public void onError(int code, String errorMessage) {
                        hideProgress();
                        showToast(errorMessage);
                    }
                });
                dialog.dismiss();
            } else {
                showToast("当前选择天数没有数据");
            }
        });
        builder.setSelectTime(year, month, day);
        EasyDialog build = builder.build();
        build.setCancelable(true);
        build.show(getSupportFragmentManager());
    }
}
